var path = require('path');
var gulp = require('gulp')
var connect = require('gulp-connect')
var less = require('gulp-less')
var babel = require('gulp-babel')
var fileinclude = require('gulp-file-include');
var del = require('del')
var replace = require('gulp-replace')
var cleanCSS = require('gulp-clean-css')
var htmlmin = require('gulp-htmlmin')
var uglify = require('gulp-uglify')
var runSequence = require('run-sequence')
var rev = require('gulp-rev')
var revCollector = require('gulp-rev-collector')
var assetRev = require('gulp-asset-rev')
var colors = require('colors')
var browserify = require('browserify') 
var through2 = require('through2')
var gulpif = require('gulp-if')
var minimist = require('minimist')
var config = require('./config')
var apiUrl,output,mock;

var knownOptions = {
	string: 'env',
	default: {env: process.env.NODE_ENV || 'development'}
}
var options = minimist(process.argv.slice(2),knownOptions);

if(!process.env.NODE_ENV) process.env.NODE_ENV = config.dev.env.NODE_ENV;

apiUrl = options.env === 'production' ? config.build.api.path : config.dev.api.path;
output = options.env === 'production' ? config.build.output.path : config.dev.output.path;
mock = options.env === 'production' ? 0 : 1;

var jsSrc = options.env === 'production' ? './build/scripts' : './dist/scripts'
var cssSrc = options.env === 'production' ? './build/styles' : './dist/styles'
var htmlSrc = options.env === 'production' ? './build/pages' : './dist/pages'

gulp.task('ver2',['revJs2'],function(){
	gulp.src(htmlSrc + '/*.html')
	.pipe(assetRev())
	.pipe(gulp.dest(htmlSrc))
	.pipe(connect.reload());
})

gulp.task('revJs2',function(){
	return gulp.src(jsSrc + '/*.js')
		.pipe(assetRev())
		.pipe(gulp.dest(jsSrc))
})

gulp.task('revCss2',function(){
	return gulp.src(cssSrc + '/*.css')
		.pipe(assetRev())
		.pipe(gulp.dest(cssSrc))
})

function compress(env){
	if(env === 'production'){
		console.log('压缩')
	}
}

gulp.task('connect',function(){
	connect.server({
		root: './dist',
		livereload: true,
		port: 3001
	})
})

gulp.task('reload',function(){
	gulp.src(htmlSrc + '/*.html')
	/*.pipe(connect.reload());*/
})

gulp.task('api:dev',function(){
	gulp.src('./api/*.json')
	.pipe(gulp.dest('./dist/api/'))
})

gulp.task('img:dev',function(){
	gulp.src('./src/images/*.@(png|jpg|gif)')
	.pipe(gulp.dest(output + 'images/'))
})

gulp.task('html:dev',['less:dev','js:dev'],function(){
	return gulp.src('./src/pages/main/*.html')
	.pipe(fileinclude({
		prefix: '@@'
	})) 
	.pipe(replace(/\%\{url\}/g,function(){
		return apiUrl;
	}))
	.pipe(replace(/\%\{data\}/,function(){
		return mock;
	}))
	.pipe(gulp.dest(output + 'pages/'))
	.pipe(connect.reload())
})

gulp.task('less:dev',function(){
	if(options.env === 'production'){
		gulp.src('./src/styles/page/*.less')
		.pipe(less())

		/*
		.pipe(cleanCSS({debug: true},function(details){
			console.log(details.name + ':' + details.stats.originalSize);
			console.log(details.name + ':' + details.stats.minifiedSize);
		}))*/
		.pipe(gulp.dest(output + 'styles/'))
	} else {
		return gulp.src('./src/styles/page/*.less')
		.pipe(less())
		.pipe(gulp.dest(output + 'styles/'))
	}
	
})

gulp.task('js:dev',function(){
	if(options.env === 'production'){
		gulp.src('./src/scripts/page/*.js')
		.pipe(through2.obj(function(chunk,enc,callback){
			browserify(chunk.path,{
				debug: true
			}) 
			.bundle(function(err,res){
				if (err) {
	                console.log('browserify 编译失败'.error, err);
	                return;
	            } else {
	            	chunk.contents = res;
	            	callback(null, chunk);
	            }
	            
			})
		}))
		.pipe(babel()) 
		/*.pipe(uglify())*/
		.pipe(gulp.dest(output +  'scripts/'))
	} else {
		gulp.src('./src/scripts/page/*.js')
		.pipe(through2.obj(function(chunk,enc,callback){
			browserify(chunk.path,{
				debug: false
			})
			.bundle(function(err,res){
				if (err) {
	                console.log('browserify 编译失败'.error, err);
	                return;
	            } else {
	            	chunk.contents = res;
	            	callback(null, chunk);
	            }
			})
		}))
		.pipe(babel())
		.pipe(gulp.dest(output +  'scripts/'))
	}
})

gulp.task('watch:dev',function(){
	gulp.watch(['./src/pages/main/*.html'],['html:dev'])
	gulp.watch(['./src/styles/page/*.less'],['html:dev'])
	gulp.watch(['./src/scripts/page/*.js'],['html:dev'])
	gulp.watch(['./api/*.json'],['api:dev'])
})

gulp.task('clean',function(cb){
	del('./dist')
	del('./build')
})


var devTask = ['connect','watch:dev','html:dev','img:dev','api:dev',],
	buildTaks = ['html:dev','img:dev'];

var defaultTaks = options.env === 'production' ? buildTaks : devTask;

gulp.task('start',defaultTaks);
